import 'dart:isolate';

main() {
  multiThread();
}

void multiThread() async {
  print('multiThread start');
  print('当前线程：'+Isolate.current.debugName);

  ReceivePort r1 = ReceivePort();
  SendPort p1 = r1.sendPort;

  Isolate.spawn(newThread, p1);

  // 接受新线程发送过来的消息
  // var msg = r1.first;
  // print('来自新线程的消息：'+msg.toString());

  // r1.listen((msg) {
  //   print('来自新线程的消息：'+msg.toString());
  //   r1.close();
  // });

  SendPort p2 = await r1.first;
  // p2.send('来自主线程的消息');

  var msg = await sendToReceive(p2, 'hello');
  print('主线程接收到：$msg');
  var msg1 = await sendToReceive(p2, 'world');
  print('主线程接收到：$msg1');

  print('multiThread end');
}

void newThread(SendPort p1) async {
  print('当前线程：'+Isolate.current.debugName);
  ReceivePort r2 = ReceivePort();
  SendPort p2 = r2.sendPort;

  // 发送消息给 main 线程
  // p1.send('abc');
  p1.send(p2);

  // r2.listen((message) {
  //   print(message);
  // });
  await for (var msg in r2) {
    var data = msg[0];
    print('新线程收到了来自主线程的消息： $data');
    SendPort replyPort = msg[1];
    // 给主线程回复消息
    replyPort.send(data);
  }
}

Future sendToReceive(SendPort port, msg) {
  print('发送消息给新线程：'+msg.toString());
  ReceivePort response = ReceivePort();
  port.send([msg, response.sendPort]);
  return response.first;
}